package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import com.sky.vo.DishVO;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    @Override
    public List<ShoppingCart> list() {
        return shoppingCartMapper.list();
    }

    @Override
    public void save(ShoppingCartDTO shoppingCartDTO) {
        //补充 商品名称 照片 UserId 数量（累加） 金额（累加） 创建时间
        //1判断商品类别
        ShoppingCart shoppingCart = new ShoppingCart();
        //复制属性
        BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
        if (shoppingCartDTO.getDishId() != null){//菜品
            ShoppingCart s1 =shoppingCartMapper.getById(shoppingCartDTO.getDishId());
            if(s1 != null){
                s1.setNumber(s1.getNumber()+1);
//                s1.setAmount(s1.getAmount().add(dishMapper.getById(shoppingCartDTO.getDishId()).getPrice()));
                shoppingCartMapper.update(s1);
                return;
            }
            DishVO dishVO = dishMapper.getById(shoppingCartDTO.getDishId());
            shoppingCart.setName(dishVO.getName());
            shoppingCart.setImage(dishVO.getImage());
            //金额
            shoppingCart.setAmount(dishVO.getPrice());
        }else if(shoppingCartDTO.getSetmealId() != null){//套餐
            ShoppingCart s2 =shoppingCartMapper.getById(shoppingCartDTO.getSetmealId());
            if(s2 != null){
                s2.setNumber(s2.getNumber()+1);
//                s2.setAmount(s2.getAmount().add(setmealMapper.getById(shoppingCartDTO.getSetmealId()).getPrice()));
                shoppingCartMapper.update(s2);
                return;
            }
            SetmealVO setmealVO = setmealMapper.getById(shoppingCartDTO.getSetmealId());
            shoppingCart.setName(setmealVO.getName());
            shoppingCart.setImage(setmealVO.getImage());
            shoppingCart.setAmount(setmealVO.getPrice());
        }
        shoppingCart.setUserId(BaseContext.getCurrentId());
        shoppingCart.setCreateTime(LocalDateTime.now());
        shoppingCartMapper.save(shoppingCart);
    }
}
